import { StatusCodes } from 'http-status-codes';
import { ApiError } from '../utils/ApiError';

/**
 * 创建标准化错误对象
 */
export function createError(
  statusCode: number = StatusCodes.INTERNAL_SERVER_ERROR,
  message: string = 'An unexpected error occurred',
  details?: Record<string, any>
): ApiError {
  return new ApiError(statusCode, message, details);
}

// 标准错误工厂函数
export const Errors = {
  badRequest: (message: string = 'Bad request', details?: Record<string, any>) => 
    createError(StatusCodes.BAD_REQUEST, message, details),

  unauthorized: (message: string = 'Unauthorized', details?: Record<string, any>) => 
    createError(StatusCodes.UNAUTHORIZED, message, details),

  forbidden: (message: string = 'Forbidden', details?: Record<string, any>) => 
    createError(StatusCodes.FORBIDDEN, message, details),

  notFound: (message: string = 'Resource not found', details?: Record<string, any>) => 
    createError(StatusCodes.NOT_FOUND, message, details),

  conflict: (message: string = 'Resource conflict', details?: Record<string, any>) => 
    createError(StatusCodes.CONFLICT, message, details),

  validationError: (message: string = 'Validation error', details?: Record<string, any>) => 
    createError(StatusCodes.UNPROCESSABLE_ENTITY, message, details),

  internal: (message: string = 'Internal server error', details?: Record<string, any>) => 
    createError(StatusCodes.INTERNAL_SERVER_ERROR, message, details)
};

export class ValidationError extends ApiError {
  constructor(message: string, details?: Record<string, any>) {
    super(StatusCodes.UNPROCESSABLE_ENTITY, message, details);
  }
}

export class AuthenticationError extends ApiError {
  constructor(message: string = 'Authentication failed') {
    super(StatusCodes.UNAUTHORIZED, message);
  }
}

export class AuthorizationError extends ApiError {
  constructor(message: string = 'Permission denied') {
    super(StatusCodes.FORBIDDEN, message);
  }
}

export class ResourceNotFoundError extends ApiError {
  constructor(resource: string, id?: string | number) {
    const message = id 
      ? `${resource} with id ${id} not found`
      : `${resource} not found`;
    super(StatusCodes.NOT_FOUND, message);
  }
}

export class ResourceConflictError extends ApiError {
  constructor(resource: string, details?: Record<string, any>) {
    super(StatusCodes.CONFLICT, `${resource} already exists`, details);
  }
}
